package ws.utils.io;

import java.io.DataInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;

/**
 * This class provides some utilities to read data from an {@link DataInputStream}.
 *
 * @author Wilson Santos, 36228 <wilson.santos@ua.pt>
 */
public class LittleEndianDataInputStream {
  private DataInputStream is;

  public LittleEndianDataInputStream(DataInputStream is) {
    assert is != null;
    this.is = is;
  }

  public byte readByte() throws IOException {
    return is.readByte();
  }

  public short readShort() throws IOException {
    final int shortSize = 2;
    byte[] tmp = new byte[shortSize];
    is.read(tmp, 0, shortSize);
    return ByteBuffer.allocate(tmp.length).order(ByteOrder.LITTLE_ENDIAN).put(tmp).getShort(0);
  }

  public int readInt() throws IOException {
    final int intSize = 4;
    byte[] tmp = new byte[intSize];
    is.read(tmp, 0, intSize);
    return ByteBuffer.allocate(tmp.length).order(ByteOrder.LITTLE_ENDIAN).put(tmp).getInt(0);
  }

  public int readIntAsSent() throws IOException {
    return is.readInt();
  }

  public long readLong() throws IOException {
    final int longSize = 8;
    byte[] tmp = new byte[longSize];
    is.read(tmp, 0, longSize);
    return ByteBuffer.allocate(tmp.length).order(ByteOrder.LITTLE_ENDIAN).put(tmp).getLong(0);
  }

  public int read(byte[] bytes, int offset, int length) throws IOException {
    return is.read(bytes, offset, length);
  }

  public int skipBytes(int n) throws IOException {
    return is.skipBytes(n);
  }
}
